<?php

use Illuminate\Database\Capsule\Manager as DB;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;

#[店铺后台菜单管理]
class Dianpu_MenusController extends AcommonController
{

    public function init()
    {
        $this->model      = (new \app\modules\Admin\models\merchantmenusModel());
        $this->table      = 'merchant_menus';
        $this->primaryKey = 'id';
        parent::init();
    }

    #[菜单添加]
    public function addAction()
    {
        if(!$this->isPost()) {
            $authlist      = [];
            $filenames     = scandir(controllerFile('', 'Merchant'));
            foreach ($filenames as $v) {
                if (preg_match('/\.php$/', $v)) {
                    $controller = substr($v, 0, -4);
                    $authlist[] = $this->getact($controller);
                }else{
                    if($v !== '.' && $v !== '..'){
                        $sub_filenames = scandir(controllerFile($v.'+', 'Merchant'));
                        foreach($sub_filenames as $sub_v){
                            if(preg_match('/\.php$/', $sub_v)){
                                $controller = $v.'_'.substr($sub_v, 0, -4);
                                $authlist[] = $this->getact($controller);
                            }
                        }
                    }
                }
            }
            $this->_view->assign('authlist', $authlist);
            $mainMenu = $this->model->where('up', '=', 0)->orderBy('sortorder', 'desc')->get();
            foreach($mainMenu as $k=>&$v){
                $v->children = $this->model->where('up', '=', $v->id)->orderBy('sortorder', 'desc')->get();
            }
            $this->_view->assign('module', 'Merchant');
            $this->_view->assign('mainMenu', $mainMenu);
            $this->_view->display('dianpu_menus/add.html');
        }else{
            parent::addAction();
        }
    }

    #[获取店铺控制器方法]
    public function getactsAction()
    {
        do {
            $id         = $this->get('id');
            $module     = $this->get('module', 'Merchant');
            $controller = $this->get('controller');
            $dataset    = $this->model->find(intval($id));
            $actions    = explode(',', $dataset->actions);
            $rows       = [['id' => '', 'text' => '【全选】', 'children' => []]];
            if (empty($controller)) {
                $result = [
                    'ret'  => 0,
                    'msg'  => '空控制器',
                    'data' => [],
                ];
                break;
            }
            include_once(controllerFile($controller, $module));
            $reflector = new ReflectionClass($controller . 'Controller');

            foreach ($reflector->getMethods(ReflectionMethod::IS_PUBLIC) as $k => $v) {
                if (substr($v->name, -6)==='Action') {
                    $value = strtolower(substr($v->name, 0, -6));
                    if ($v->getAttributes()) {
                        $name = $v->getAttributes()[0]->getName();
                    } else {
                        $name = $value;
                    }
                    array_push($rows[0]['children'], ['id' => $value, 'text' => $name, 'checked' => in_array($value, $actions)]);
                }
            }
            $result = [
                'ret'  => 0,
                'msg'  => '控制器方式列表',
                'data' => $rows,
            ];
        } while (FALSE);
        json($result);
    }

    private function getact(string $controller = '', array $actions = [])
    {
        do {
            if (empty($controller)) {
                break;
            }
            $controllerName = $controller;
            require_once(controllerFile($controller, 'Merchant'));
            if(class_exists($controller.'Controller')) {
                $reflector = new ReflectionClass($controller . 'Controller');
                if ($reflector->getAttributes()) {
                    $controllerName = $reflector->getAttributes()[0]->getName();
                }
            }
        } while (FALSE);
        return ['name' => $controllerName, 'value' => $controller];
    }

    #[获取店铺主菜单]
    public function menusGetAction()
    {
        json(['ret' => 0, 'rows' => $this->model->where('up', '=', 0)->orderBy('sortorder', 'desc')->get()]);
    }

    #[菜单列表]
    public function indexAction($returnData = FALSE)
    {
        if($this->isPost()){
            $page     = $this->get('page', 1);
            $limit    = $this->get('rows', 10);
            $offset   = ($page - 1) * $limit;
            $sort     = $this->get('sort', 'sortorder');
            $order    = $this->get('order', 'desc');
            $keywords = trim($this->get('keywords', ''));
            $query    = $this->model->where('up', '=', 0);
            if ($keywords !== '') {
                $query = $query->where('name', 'like', "%{$keywords}%");
            }
            $total = $query->count();
            $rows  = $query->orderBy($sort, $order)
                           ->offset($offset)
                           ->limit($limit)
                           ->get();
            if ($rows->isNotEmpty()) {
                \app\modules\Admin\service\Dianpumenus::getAllChildren($rows, 'up');
            }
            json(['total' => $total, 'rows' => $rows]);
        }else{
            $this->_view->display('dianpu_menus/menus.html');
        }
    }

    #[菜单编辑]
    public function editAction()
    {
        if(!$this->isPost()) {
            $id = $this->get('id', NULL);
            if ($id == NULL) return FALSE;
            $dataset       = $this->model->find(intval($id));
            $authlist      = [];
            $filenames     = scandir(controllerFile('', 'Merchant'));
            foreach ($filenames as $v) {
                if (preg_match('/\.php$/', $v)) {
                    $controller = substr($v, 0, -4);
                    $authlist[] = $this->getact($controller);
                }else{
                    if($v !== '.' && $v !== '..'){
                        $sub_filenames = scandir(controllerFile($v.'+', 'Merchant'));
                        foreach($sub_filenames as $sub_v){
                            if(preg_match('/\.php$/', $sub_v)){
                                $controller = $v.'_'.substr($sub_v, 0, -4);
                                $authlist[] = $this->getact($controller);
                            }
                        }
                    }
                }
            }
            $this->_view->assign('authlist', $authlist);
            $this->_view->assign('dataset', json_encode($dataset));
            $mainMenu = $this->model->where('up', '=', 0)->orderBy('sortorder', 'desc')->get();
            foreach($mainMenu as $k=>&$v){
                $v->children = $this->model->where('up', '=', $v->id)->orderBy('sortorder', 'desc')->get();
            }
            $this->_view->assign('module', 'Merchant');
            $this->_view->assign('mainMenu', $mainMenu);
            $this->_view->display('dianpu_menus/edit.html');
        }else{
            parent::editAction();
            $merchant_managers = \app\modules\Admin\models\merchantModel::query()->pluck('id')->toArray();
            if(!empty($merchant_managers)){
                foreach ($merchant_managers as $m_id){
                    forget('merchant_auths_' . $m_id);
                }
            }
            unset($merchant_managers, $m_id);
        }
    }

    #[菜单删除]
    public function deleteAction()
    {
        do {
            if ($this->method != 'POST') {
                $result = [
                    'ret' => 1,
                    'msg' => '操作失败',
                ];
                break;
            }
            $id = $this->get('id', '');
            if (empty($id)) {
                $result = [
                    'ret' => 2,
                    'msg' => '参数为空',
                ];
                break;
            }
            if($this->model->where('up', $id)->exists()){
                $result = [
                    'ret' => 3,
                    'msg' => '下级菜单非空',
                ];
                break;
            }
            if ($this->model->delete($id)) {
                $result = [
                    'ret' => 0,
                    'msg' => '操作成功',
                ];
            } else {
                $result = [
                    'ret' => 4,
                    'msg' => '删除失败',
                ];
            }
        } while (FALSE);

        json($result);
    }
}
